package com.aruba.workmanager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkContinuation;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;
import androidx.work.WorkRequest;

import android.os.Bundle;
import android.util.Log;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //设置条件
        Constraints constraints = new Constraints.Builder()
                //NetworkType.CONNECTED:需要有网络
                //NetworkType.NOT_REQUIRED:不需要网络
                //NetworkType.NOT_ROAMING:非漫游网络
                //NetworkType.METERED:计费网络下执行（流量）
                //NetworkType.UNMETERED:不计费网络（wifi）
                .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
//                .setRequiresBatteryNotLow(true)//不在低电量
//                .setRequiresCharging(true)//充电时执行
//                .setRequiresStorageNotLow(true)//不在低存储空间
//                .setRequiresDeviceIdle(true)//不在待机 api23
                .build();

        Data data = new Data.Builder()
                .putString("createTask", "createTask")
                .build();

        //配置任务
        OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWork.class)
                .setConstraints(constraints)
                //设置延迟
                .setInitialDelay(5, TimeUnit.SECONDS)
                //指数退避策略
                .setBackoffCriteria(BackoffPolicy.LINEAR, 2, TimeUnit.SECONDS)
                //设置tag
                .addTag("work1")
                //传入参数
                .setInputData(data)
                .build();

        //周期性任务
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest
                    .Builder(MyWork.class, Duration.ofMinutes(15))
                    .build();
        }

        //任务入队
        WorkManager workManager = WorkManager.getInstance(this);
        workManager.enqueue(workRequest);

        //添加任务监听
        workManager.getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
            @Override
            public void onChanged(WorkInfo workInfo) {
                Log.i("WorkInfo", workInfo.toString());

                if (workInfo != null && workInfo.getState() == WorkInfo.State.SUCCEEDED) {
                    String doWork = workInfo.getOutputData().getString("doWork");
                    Log.i("WorkInfo", doWork);
                }
            }
        });

//        //取消任务
//        workManager.cancelWorkById(workRequest.getId());

//        OneTimeWorkRequest aWork = new OneTimeWorkRequest.Builder(AWork.class)
//                .build();
//        OneTimeWorkRequest bWork = new OneTimeWorkRequest.Builder(BWork.class)
//                .build();
//        //先执行A再执行B
//        workManager.beginWith(aWork).then(bWork).enqueue();

        OneTimeWorkRequest aWork = new OneTimeWorkRequest.Builder(AWork.class)
                .build();
        OneTimeWorkRequest bWork = new OneTimeWorkRequest.Builder(BWork.class)
                .build();
        OneTimeWorkRequest cWork = new OneTimeWorkRequest.Builder(CWork.class)
                .build();
        OneTimeWorkRequest dWork = new OneTimeWorkRequest.Builder(DWork.class)
                .build();
        OneTimeWorkRequest eWork = new OneTimeWorkRequest.Builder(EWork.class)
                .build();

        //先A再B
        WorkContinuation workContinuation1 = workManager.beginWith(aWork).then(bWork);
        //先C再D
        WorkContinuation workContinuation2 = workManager.beginWith(cWork).then(dWork);

        List<WorkContinuation> workContinuations = new ArrayList<>();
        workContinuations.add(workContinuation1);
        workContinuations.add(workContinuation2);

        //最后执行E
        WorkContinuation.combine(workContinuations).then(eWork).enqueue();
    }
}